# === 配置部分 ===
$ProjectPath = "D:\school_project\single-slope"
$TargetFile = "D:\school_project\single-slope\ruoyi-admin\target\ruoyi-admin.jar"
$ServerUser = "root"
$ServerIp = "39.107.238.187"
$ServerDir = "/www/wwwroot/psy/psy-back"
$JarName = "ruoyi-admin.jar"
$LogFile = "ruoyi.log"

# === Maven 打包 ===
Write-Output "===== Begin Maven package ====="
cd $ProjectPath
& mvn clean package -DskipTests | ForEach-Object { Write-Host $_ }
if ($LASTEXITCODE -ne 0) {
    Write-Error "Maven fail!"
    exit $LASTEXITCODE
}

# === 上传到临时文件 ===
$TempFile = "${ServerDir}/${JarName}.new"
Write-Output "===== Uploading to temporary file on server ====="
scp -o StrictHostKeyChecking=no $TargetFile "${ServerUser}@${ServerIp}:$TempFile"
if ($LASTEXITCODE -ne 0) {
    Write-Error "SCP upload fail!"
    exit $LASTEXITCODE
}

# === 删除旧 JAR 文件 ===
Write-Output "===== Removing old JAR files ====="
ssh -o StrictHostKeyChecking=no "${ServerUser}@${ServerIp}" "rm -f ${ServerDir}/${JarName}"
if ($LASTEXITCODE -ne 0) {
    Write-Error "Failed to remove old JAR file!"
    exit $LASTEXITCODE
}

# === 重命名临时文件为正式文件 ===
Write-Output "===== Renaming new JAR ====="
ssh -o StrictHostKeyChecking=no "${ServerUser}@${ServerIp}" "mv -f ${TempFile} ${ServerDir}/${JarName}"
if ($LASTEXITCODE -ne 0) {
    Write-Error "Remote rename fail!"
    exit $LASTEXITCODE
}

# === 重启项目 ===
Write-Output "===== Restarting project on server ====="
ssh -o StrictHostKeyChecking=no "${ServerUser}@${ServerIp}" "cd ${ServerDir} && pkill -f ${JarName} && nohup java -jar ${JarName} > ${LogFile} 2>&1 &"
if ($LASTEXITCODE -ne 0) {
    Write-Error "Remote project restart fail!"
    exit $LASTEXITCODE
}

Write-Output "===== Deployment and restart finished ====="
